<!DOCTYPE html>
<html>
<div align="center">
<head>

<font face="Bauhaus 93" color="green" size="6" align="center">
	<link rel="stylesheet" media="screen" href="@{'/public/stylesheets/main.css'}">
	<title>taxiApp</title>
	<script src="@{'/public/javascripts/jquery-1.5.min.js'}" type="text/javascript" charset="${_response_encoding}"></script>
	<script type="text/javascript"

		src="http://maps.google.com/maps/api/js?sensor=true"
		src="http://code.jquery.com/jquery-1.8.1.js">
	</script>
	
	<script>


		var yourlocation;
		var marker;
		var provMarker; //marker of selected provider;
		var map;
        var lat = 48.45;//initail coordinates;
        var lng = 34.983333;//initial coordinates;
        var deviceSn; //Id of client device;
		var lati;
		var lngi;
		var jsonString = '{"provsList":[{"provId":"10","userId":"20","ULat":"44.9859","ULong":"9.03351","PLat":"45.4839701462306","PLong":"9.190213680267334","id":1},{"provId":"10","userId":"21","ULat":"44.9859","ULong":"9.03351","PLat":"45.475815620095226","PLong":"9.21201467514038","id":2},{"provId":"10","userId":"22","ULat":"44.9859","ULong":"9.03351","PLat":"45.450953584498954","PLong":"9.190127849578857","id":3},{"provId":"10","userId":"23","ULat":"44.9859","ULong":"9.03351","PLat":"45.46636572642042","PLong":"9.188969135284424","id":4}]}';
		var marks = new Array();
		var markers = new Array(); //array of all markers;
		var host="localhost";//'192.168.1.9';
		//var host='testmobile.tplinfo.com';
		var port='9000';
		var url='http://'+host+':'+port;

                                var yourlocation;
                                var marker;
                                var provMarker; //marker of selected provider;
                                var map;
                                var lat = 48.45;//initail coordinates;
                                var lng = 34.983333;//initial coordinates;
                                var deviceSn; //Id of client device;
                                var lati;
                                var lngi;
                                var jsonString = '{"provsList":[{"provId":"10","userId":"20","ULat":"44.9859","ULong":"9.03351","PLat":"45.4839701462306","PLong":"9.190213680267334","id":1},{"provId":"10","userId":"21","ULat":"44.9859","ULong":"9.03351","PLat":"45.475815620095226","PLong":"9.21201467514038","id":2},{"provId":"10","userId":"22","ULat":"44.9859","ULong":"9.03351","PLat":"45.450953584498954","PLong":"9.190127849578857","id":3},{"provId":"10","userId":"23","ULat":"44.9859","ULong":"9.03351","PLat":"45.46636572642042","PLong":"9.188969135284424","id":4}]}';
                                var marks = new Array();
                                var markers = new Array(); //array of all markers;
                                var host="localhost";//'192.168.1.9';
                                //var host='testmobile.tplinfo.com';
                                var port='9000';
                                var url='http://'+host+':'+port;

                                var waitEvents = url+"/user/waitEvents"; //comet request to server
                                var chooseProv = url+"/user/chooseProv";
                                var canceled = url+"/user/cancel";
                                var userDeclare = url+"/user/declared";
                                var userConfirmed = url+"/user/confirmed";
                                var signIn = url+"/user/signIn";
                                var exit = url+"/user/exit";
	    
	    var userId;
	    var provId; //id of selected provider

	    var lastReceived=0; //number of received event from server
		var timeOut = "100000000"; //
		var greenUser = "@{'/public/images/map/user_green.png'}";
		var greenTaxi = "@{'/public/images/map/taxi_green.png'}";
		var magentaTaxi = "@{'/public/images/map/taxi_magenta.png'}";
		var orangeTaxi = "@{'/public/images/map/taxi_orange.png'}";
		var redTaxi = "@{'/public/images/map/taxi_red.png'}";
		var yellowTaxi = "@{'/public/images/map/taxi_yellow.png'}";
		var clickAble = true;
                                var temp;
		
		function initialize() {
			
			//random  coordinates to initialize map
			//var latlng = new google.maps.LatLng(45.465, 9.2);
			var latlng = new google.maps.LatLng(lat, lng);
			//setting map's parameters
			var mapOptions = {

				zoom: 12,

				mapTypeId: google.maps.MapTypeId.ROADMAP,

				center: latlng

			};

				map = new google.maps.Map(document.getElementById("map_canvas"),

			    mapOptions);

			//putMarker();
		
		}

		//This method create new user: 
		//		-add new user to server DB 
		//		-put user id to current session
		//		-add user marker to map

		function createUser(){
			lat = $('#la').val();
			lng = $('#lo').val();
			deviceSn = $('#deviceSn').val();

			if((lat!='')&&(lng!='')){
				$.ajax({
			            url:signIn,
			            data:{'deviceSn':deviceSn},
			                success: function(events){

			                    userId = Number(events.userId);
                                            if(userId != -1){
                                                    putMarker("you",0, lat,lng,greenUser);
                                                    var provsId = events.provsId;
                                                    var coordinates = events.coordinates;
                                                    var status = events.status;

                                                    for(id in provsId){
                                                        if(status[id] == "u_requested"){
                                                                putMarker("requested",provsId[id],coordinates[id].x,coordinates[id].y,yellowTaxi);
                                                        }
                                                        else{
                                                                putMarker("declared",provsId[id],coordinates[id].x,coordinates[id].y,greenTaxi);
                                                        }

                                                    }
                                                    manager();
                                                    document.getElementById("crtUserM").style.display = 'none';
                                            }
                                            else{
                                                    alert("The deviceSn you entered is incorrect");
                                            }
			                },
			                dataType: 'json'
			        });
				
				return true;
			}
			alert("You don't write coordinates of client");	
			
			
			
		}
		// This function used for get and manage new events from server
		function manager(){
	        // Retrieve new messages
	        
	        var getEvents = function() {
	            $.ajax({
	                url: waitEvents,
	                data: {lastReceived:lastReceived, userId:userId},
	                success: function(events) {
	                    $(events).each(function() {
	                        lastReceived = this.id;
	                        eventManager(this.data);
	                    })
	                    getEvents()
	                },
	                dataType: 'json'
	            });
	        }
	        getEvents();
	        //manage events from server
	        function eventManager(event){
	            if(event.status == "u_requested"){
	                for(i in markers){
	                	if(markers[i].id == event.provId){
	                		markers[i].setTitle("requested");
	                		markers[i].setIcon(yellowTaxi);
	                	}
	                }
	            }

                                                if(event.status == "p_declared"){
                                                        putMarker("declared", event.provId,event.coordinates.x,event.coordinates.y,greenTaxi);
                                                }
                                                if(event.status == "u_confirmed"){
                                                        if(userId != event.userId){
                                                                if(provId == event.provId){
                                                                        alert("Sorry, but provider choose another user. Please select new provider");
                                                                        clickAble = true;
                                                                        provMarker.setMap(null);
                                                                }
                                                                else{
                                                                        for(i in markers){
                                                                                if(markers[i].id == event.provId){
                                                                                        markers[i].setVisible(false);
                                                                                }
                                                                        }
                                                                }
                                                        }
                                                        else{
                                                                temp.setTitle("confirmed");
                                                                temp.setIcon(magentaTaxi);
                                                                provMarker = temp;
                                                                hideOtherMarkers(temp.id);
                                                        }
                                                }
                                                if(event.status == "p_accepted"){
                                                        
                                                        for(i in markers){
                                                                if(markers[i].id == event.provId){
                                                                        temp = markers[i];
                                                                        markers[i].setTitle("accepted");
                                                                        markers[i].setIcon(orangeTaxi);
                                                                }
                                                        }
                                                        if(confirm("Prov - accept. His data: inf - "+event.serviceInf+" time - "+event.time)){
                                                                
                                                                $.post(userConfirmed,{provId:provId,userId:userId,lat:lat,lng:lng});
                                                        }
                                                        else{
                                                                alert("Please choose new provider");
                                                                temp.setMap(null);
                                                                $.post(canceled,{provId:provId,userId:userId});
                                                                clickAble = true;
                                                                provId = -1;
                                                                //delProv(provId);
                                                        }
                                                }
                                                if((event.status == "p_acceptedCanceled") && (event.provId == provId)){
                                                        alert("Provider with id " + event.provId + " don't accept request");
                                                        clickAble = true;
                                                        provMarker.setMap(null);
                                                        for(i in markers){
                                                                if(markers[i].id == event.provId){
                                                                        markers[i].setMap(null);
                                                                }
                                                        }
                                                        provId = -1;
                                                }
                                                if (event.status == "u_canceled") {
                                                        alert("You don't confirm request for provider with id "
                                                                + event.provId);
                                                        clickAble = true;
                                                        provMarker.setMap(null);
                                                        for(i in markers){
                                                                if(markers[i].id == event.provId){
                                                                        markers[i].setMap(null);
                                                                }
                                                        }
                                                        provId = -1;
                                                }
                                                if(event.status =="p_locked"){
                                                        alert('You was locked');
                                                        provMarker.setIcon(redTaxi);
                                                }
                                                if(event.status == "p_reached"){
                                                        alert('Prov reached distance');
                                                        provId = -1;
                                                        document.getElementById("uExit").style.display = "inline";
	                
	                
	            }       
	        }

	    }

	function hideOtherMarkers(id){
		for(i in markers){
        	if(markers[i].id != id){
        		markers[i].setVisible(false);
        	}
        }	
	}
	//must be call when user exit from system
	function uExit(){
		lastReceived = 0;
         $.ajax({
                url: exit,
                data: {userId:userId},
                success: function(events) {
                    document.location.reload();
                },
                dataType: 'json'
            });
		// $.post(exit,{userId:userId});
		
	}
	
	//with two parameters (latitude & longitude) this function finds you on the map and puts a marker in the exact position you set.
    function putMarker(title,id, lat, lng,image) {
      //take parameters from edit box
		//lat = document.getElementById("la").value
        //lng = document.getElementById("lo").value
			yourlocation = new google.maps.LatLng(lat, lng);
			//set map's center on the user's location
			map.setCenter(yourlocation);

                                                var flag = 0;
                                                for(i in markers){
                                                        if(markers[i].id == id){
                                                               flag++;
                                                               markers[i].setIcon(image);
                                                               markers[i].setTitle(title);
                                                               if (markers[i].id != provId){
                                                                       markers[i].setVisible(true);
                                                               }
                                                        }
                                                }

			if(flag == 0){
			//marker's options
                                                        marker = new google.maps.Marker({

                                                                        icon: image,

                                                                        map:map,

                                                                        draggable:true,

                                                                        animation: google.maps.Animation.DROP,

                                                                        position: new google.maps.LatLng(lat, lng),


                                                                        title: title,
                                                                        id: id

                                                        });
                                                }
			
			
			
			//add to markers of providers click-event
			if(title != 'you'){

                                                                if(flag == 0){
                                                                        markers.push(marker);
                                                                }

				google.maps.event.addListener(marker, "click", function() {
					if(clickAble == true){
						provId = this.id;
						provMarker = this;
                        var timeOut = prompt("Enter timeout please","100");
						$.post(chooseProv,{provId:provId,userId:userId,timeOut:timeOut,u_lat:lat,u_long:lng});
						clickAble = false;	
					}
					else{
						alert('You can choose only one provider!');
					}
				});

			}
			
			
			
	}
	
	//find user's geolocation and set the center of the map on his cordinates
	function gotPosition(pos)  {
	
		lati = pos.coords.latitude;
        lngi = pos.coords.longitude;
			yourlocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
			map.setCenter(yourlocation);
			
			
		}
		//this function puts some markers on the map (one for user and the others for taxis)
		function setTaxiPosition() {
		
		document.getElementById("lo").value = lngi;
		document.getElementById("la").value = lati;
		map.setCenter(yourlocation);
			
			//marker's options
			marker = new google.maps.Marker({

				map:map,
				
				icon:'user_blue.png',

				draggable:true,
				
				title:"You're here",

				animation: google.maps.Animation.DROP,

				position: yourlocation

			});
			
			
			
			//Json parsing and extraction of needed paramiters
			var contact = JSON.parse(jsonString);
			//this for-cycle will add markers for every taxi available at the moment of the request
			for(i=0; i < contact.provsList.length; i++){
			//extract userId
			var title = contact.provsList[i].userId;
			//extract coordinates
			var ps = new google.maps.LatLng(contact.provsList[i].PLat, contact.provsList[i].PLong);
			//set the marker for the position
			var marks = new google.maps.Marker({
			
			title: "Taxi n."+title+"",
			position: ps, 
			draggable:true,
			animation: google.maps.Animation.DROP,
			map: map, 
			//the taxi color is defined by its availability. See status diagram flow
			icon: 'taxi_green.png', 
			flat: true
				
				}
			);
			marks[i] = marker; 
			}
			
			
			}
			
			//errors management
			function errorGettingPosition(err) {

			if(err.code == 1) {

				alert("Geolocation not allowed");

			} else if(err.code == 2) {

				alert("Position not available");

			} else if(err.code == 3) {

				alert("Timeout");

			} else {

				alert("ERROR:" + err.message);

			}

		}

	
</script>

</font>
</head>

<body onload="initialize()" bgcolor="green">
<table align="center">
<tr><td>		
</font>
	</div>
<br><br><br><br>
	<div  id="map_canvas" style="height: 400px; width: 600px; float: center;"></div>


</td><td><div align="left">
  <div id="crtUserM">
	  Latitudine: &nbsp&nbsp&nbsp<input type="text" name="la" id="la" value="48.45" ><br>
	  Longitudine: <input type="text" name="lo" id="lo" value="34.983333" ><br>
	  deviceSn: &nbsp&nbsp&nbsp&nbsp<input type="text" name="deviceSn" id="deviceSn" value="${deviceSn}"><br>
	  <input type="button" value="Sign in" onclick="createUser()"><br>
          <input type="button" value="Registration" onclick="location.href='@{Application.userRegistration()}'"/><br/>
  </div>
  <input type="button" id="uExit" value="Exit" onclick="uExit()"/><br/>

  
</td></tr>

</table>
</body></div></html>